package ch.reevolt.charger;

import java.util.Timer;
import java.util.TimerTask;

import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.NumericWheelAdapter;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import ch.reevolt.android.graphics.widget.ButtonImageView;
import ch.reevolt.android.graphics.widget.ButtonImageView.Behavior;
import ch.reevolt.android.graphics.widget.ButtonImageView.OnClickedListener;
import ch.reevolt.charger.service.ChargerService;
import ch.reevolt.charger.service.IChargerService;
import ch.reevolt.charger.service.IChargerServiceListener;

/**
 * 
 * @author Romain Cherix
 */
public class SafeChargerActivity extends Activity implements
		IChargerServiceListener, OnClickedListener {

	private ButtonImageView lockButton;

	private Bitmap lock;
	private Bitmap unlock;

	private String P1 = "p1";
	private String P2 = "p2";
	private String P3 = "p3";
	private String P4 = "p4";
	private String LOCKED = "state";

	private Handler h;
	private int numberOfWizz = 5;
	private int wizzCounter = 0;

	private int NOTIFICATION_ID = 124578;

	private int p1, p2, p3, p4;

	private boolean firstLocked = true;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Check whether we're recreating a previously destroyed instance
		if (savedInstanceState != null) {
			// Restore value of members from saved state
			p1 = savedInstanceState.getInt(P1);
			p2 = savedInstanceState.getInt(P2);
			p3 = savedInstanceState.getInt(P3);
			p4 = savedInstanceState.getInt(P4);
			lockButton.setEnable(savedInstanceState.getBoolean(LOCKED));
			if (lockButton.isEnable())
				lockButton.setImageBitmap(lock);

		}

		initWheel(R.id.passw_1);
		initWheel(R.id.passw_2);
		initWheel(R.id.passw_3);
		initWheel(R.id.passw_4);

		// start service
		startService(new Intent(SafeChargerActivity.this, ChargerService.class));

		lockButton = (ButtonImageView) findViewById(R.id.button);
		lockButton.setOnClickedListener(this);
		lockButton.setBehavior(Behavior.SWITCH);
		lockButton.setAlphaValueDisabled(100);
		lockButton.setAlphaValueEnabled(100);
		lockButton.setEnable(false);

		lock = BitmapFactory.decodeResource(getResources(), R.drawable.lock);
		unlock = BitmapFactory
				.decodeResource(getResources(), R.drawable.unlock);

		final TranslateAnimation animLeft2Right = new TranslateAnimation(0, 20,
				0, 0);
		animLeft2Right.setInterpolator(new LinearInterpolator());
		animLeft2Right.setDuration(50);

		final TranslateAnimation animRight2Left = new TranslateAnimation(-20,
				0, 0, 0);
		animRight2Left.setInterpolator(new LinearInterpolator());
		animRight2Left.setDuration(50);

		final LinearLayout button_layout = (LinearLayout) findViewById(R.id.layout_button);

		h = new Handler() {
			boolean position = true;

			@Override
			public void handleMessage(Message msg) {
				if (position)
					button_layout.startAnimation(animLeft2Right);
				else
					button_layout.startAnimation(animRight2Left);
				position = !position;
			}
		};

	}

	public void wizz() {
		Timer t = new Timer();
		t.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				h.sendEmptyMessage(0);
				wizzCounter += 1;
				if (wizzCounter == numberOfWizz) {
					wizzCounter = 0;
					this.cancel();
				}
			}
		}, 0, 50);
		Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		v.vibrate(400);
	}

	@Override
	public void onBackPressed() {
		startActivity(new Intent(Intent.ACTION_MAIN)
				.addCategory(Intent.CATEGORY_HOME));
	}

	public void onPause() {
		super.onPause();
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		// Save the user's current game state
		savedInstanceState.putInt(P1, p1);
		savedInstanceState.putInt(P2, p2);
		savedInstanceState.putInt(P3, p3);
		savedInstanceState.putInt(P4, p4);
		savedInstanceState.putBoolean(LOCKED, lockButton.isEnable());

		// Always call the superclass so it can save the view hierarchy state
		super.onSaveInstanceState(savedInstanceState);
	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {
		// Always call the superclass so it can restore the view hierarchy
		super.onRestoreInstanceState(savedInstanceState);

		// Restore state members from saved instance
		p1 = savedInstanceState.getInt(P1);
		p2 = savedInstanceState.getInt(P2);
		p3 = savedInstanceState.getInt(P3);
		p4 = savedInstanceState.getInt(P4);
		lockButton.setEnable(savedInstanceState.getBoolean(LOCKED));

	}

	/**
	 * Initializes wheel
	 * 
	 * @param id
	 *            the wheel widget Id
	 */
	private void initWheel(int id) {
		WheelView wheel = getWheel(id);
		wheel.setViewAdapter(new NumericWheelAdapter(this, 0, 9));
		wheel.setCurrentItem((int) (Math.random() * 10));

		wheel.addScrollingListener(scrolledListener);
		wheel.setCyclic(true);
		wheel.setInterpolator(new AnticipateOvershootInterpolator());
	}

	/**
	 * Returns wheel by Id
	 * 
	 * @param id
	 *            the wheel Id
	 * @return the wheel with passed Id
	 */
	private WheelView getWheel(int id) {
		return (WheelView) findViewById(id);
	}

	// Wheel scrolled flag
	private boolean wheelScrolled = false;

	// Wheel scrolled listener
	OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
		public void onScrollingStarted(WheelView wheel) {
			wheelScrolled = true;
		}

		public void onScrollingFinished(WheelView wheel) {
			wheelScrolled = false;
		}
	};

	/**
	 * Tests entered PIN
	 * 
	 * @param v1
	 * @param v2
	 * @param v3
	 * @param v4
	 * @return true
	 */
	private boolean testPin(int v1, int v2, int v3, int v4) {
		return testWheelValue(R.id.passw_1, v1)
				&& testWheelValue(R.id.passw_2, v2)
				&& testWheelValue(R.id.passw_3, v3)
				&& testWheelValue(R.id.passw_4, v4);
	}

	/**
	 * Mixes wheel
	 * 
	 * @param id
	 *            the wheel id
	 */
	private void mixWheel(int id) {
		WheelView wheel = getWheel(id);
		wheel.scroll(-25 + (int) (Math.random() * 50), 1000);
	}

	/**
	 * Tests wheel value
	 * 
	 * @param id
	 *            the wheel Id
	 * @param value
	 *            the value to test
	 * @return true if wheel value is equal to passed value
	 */
	private boolean testWheelValue(int id, int value) {
		return getWheel(id).getCurrentItem() == value;
	}

	public void startService() {
		// Ajout de l'activity à la liste des listeners du service
		ChargerService.getService().addListener(this);
	}

	public void stopService() {
		stopService(new Intent(this, IChargerService.class));
	}

	public void dataChanged(final Object o) {
		SafeChargerActivity.this.runOnUiThread(new Runnable() {
			public void run() {

			}
		});
	}

	public void onButtonClick(View v) {

		if (lockButton.isEnable()) {
			if (testPin(p1, p2, p3, p4)) {
				lockButton.setImageBitmap(unlock);
				deleteNotification();
				firstLocked = true;
				ChargerService.getService().stopSafety();
				lockButton.setEnable(!lockButton.isEnable());
			} else {
				wizz();
			}

		} else {
			lockButton.setImageBitmap(lock);
			ChargerService.getService().startSafety();
			if (firstLocked) {
				firstLocked = false;
				p1 = getWheel(R.id.passw_1).getCurrentItem();
				p2 = getWheel(R.id.passw_2).getCurrentItem();
				p3 = getWheel(R.id.passw_3).getCurrentItem();
				p4 = getWheel(R.id.passw_4).getCurrentItem();

				mixWheel(R.id.passw_1);
				mixWheel(R.id.passw_2);
				mixWheel(R.id.passw_3);
				mixWheel(R.id.passw_4);
				lockButton.setEnable(!lockButton.isEnable());

			}
			createNotification();
		}
		

	}

	private final void createNotification() {

		final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		final Notification notification = new Notification(R.drawable.lock_not,
				"Safety charger enabled", System.currentTimeMillis());

		Intent toLaunch = new Intent(getApplicationContext(),
				SafeChargerActivity.class);
		toLaunch.setAction("android.intent.action.MAIN");
		toLaunch.addCategory("android.intent.category.LAUNCHER");

		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, toLaunch,
				PendingIntent.FLAG_UPDATE_CURRENT);

		final String notificationTitle = getResources().getString(
				R.string.notification_title);
		final String notificationDesc = getResources().getString(
				R.string.notification_desc);

		notification.setLatestEventInfo(this, notificationTitle,
				notificationDesc, pendingIntent);

		notificationManager.notify(NOTIFICATION_ID, notification);
	}

	private void deleteNotification() {
		final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(NOTIFICATION_ID);
	}

}